package com.webtest.jsptest;

import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * Create DateTime: 2018/7/10 14:30
 * @version v1.0
 */
public class HelloServlet extends HttpServlet {
    private static final String VISIT_TIME = "visitTime";
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(HelloServlet.class);
    private static final long serialVersionUID = 7379167567284235474L;

    public HelloServlet() {
        System.out.println("hellow servlet construct");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Hello Servlet init");
        super.init(config);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
        Cookie[] cookies = req.getCookies();
        boolean isFirstTime = !findCookie(cookies, VISIT_TIME);
        if (isFirstTime) {
            Cookie cookie = new Cookie(VISIT_TIME, String.valueOf(System.currentTimeMillis()));
            resp.addCookie(cookie);
            System.out.println("首次执行");
        } else {
            System.out.println("非首次执行");
        }
        System.out.println("Get方法即将执行");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        System.out.println("Post方法即将执行");
    }

    private boolean findCookie(Cookie[] cookies, String key) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                return true;
            }
        }
        return false;
    }
}
